'use strict'
const path = require('path')
const defaultSettings = require('./src/settings.js')
const Components = require('unplugin-vue-components/webpack')
const TerserPlugin = require('terser-webpack-plugin')
function resolve(dir) {
  return path.join(__dirname, dir)
}

const name = defaultSettings.title || '后台权限管理系统' // page title
const port = process.env.port || process.env.npm_config_port || 9528 // dev port
const isProd = process.env.NODE_ENV === 'production' // 判断是否是生产环境
const externals = {//外链
  'vue': 'Vue',
  'vue-router': 'VueRouter',
  'vuex': 'Vuex',
  'axios': 'axios',
  'element-ui': 'ELEMENT',
  'xlsx': 'XLSX',
  'nprogress': 'NProgress',
  'dayjs': 'dayjs',
  'js-cookie': 'Cookies',
  'screenfull': 'screenfull',
  'cos-js-sdk-v5': 'COS',
}
const CDN = {
  css: [
    'https://unpkg.com/nprogress@0.2.0/nprogress.css',
    'https://unpkg.com/element-ui@2.15.12/lib/theme-chalk/index.css',
    'https://unpkg.com/normalize.css@8.0.1/normalize.css',
  ],
  js: [
    'https://unpkg.com/vue@2.6.10/dist/vue.min.js',
    'https://unpkg.com/vue-router@3.0.6/dist/vue-router.min.js',
    'https://unpkg.com/vuex@3.1.0/dist/vuex.min.js',
    'https://unpkg.com/element-ui@2.15.12/lib/index.js',
    'https://unpkg.com/axios@1.3.4/dist/axios.min.js',
    'https://unpkg.com/xlsx@0.18.5/dist/xlsx.mini.min.js',
    'https://unpkg.com/nprogress@0.2.0/nprogress.js',
    'https://unpkg.com/js-cookie@2.2.0/src/js.cookie.js',
    'https://unpkg.com/screenfull@5.2.0/dist/screenfull.js',
    'https://unpkg.com/cos-js-sdk-v5@1.4.16/dist/cos-js-sdk-v5.min.js',
    'https://unpkg.com/dayjs@1.11.7/dayjs.min.js',
  ]
}

module.exports = {
  publicPath: isProd ? './' : '/',
  outputDir: 'dist',
  assetsDir: 'static',
  lintOnSave: isProd,
  productionSourceMap: false,
  /**================== 代理服务 start ==================*/
  devServer: {
    open: true,
    port,
    proxy: {
      '/api': {
        target: 'http://ihrm.itheima.net',
        changeOrigin: true,
        // pathRewrite: {
        //   // 路径重写  有需要的时候才需要写
        //   '^/api': ''
        // }
      },
    }
  },
  /**================== 代理服务 end ==================*/
  configureWebpack: {
    name: name,
    resolve: {
      alias: {
        '@': resolve('src')
      }
    },
    externals: isProd ? externals : {},
    plugins: [
      Components({
        dts: 'src/components.d.ts'// 配置自定义组件注册文件生成位置
      })
    ],

    optimization: {
      minimizer: [
        new TerserPlugin({
          parallel: 4,
          terserOptions: {
            compress: {
              warnings: true,
              drop_debugger: true, // 删除debugger
              drop_console: true  // 删除console
            }
          }
        })
      ],
    }

  },
  chainWebpack(config) {
    /**================== 公共配置 start ==================*/

    /**======== CDN start ========*/
    config.plugin('html').tap(args => {
      args[0].cdn = isProd ? CDN : { css: [], js: [] }
      return args
    })
    //======== CDN end ========

    //======== svg start ========
    config.plugin('preload').tap(() => [// 预加载 preload,提高用户操作体验
      {
        rel: 'preload',
        fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
        include: 'initial'
      }
    ])
    config.plugins.delete('prefetch')
    //======== svg start ========
    config.module
      .rule('svg')
      .exclude.add(resolve('src/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()
    //======== svg end ========


    /**================== 公共配置 end ==================*/

    /**================== 生产环境 start ==================*/
    if (isProd) {
      config.entry('app').clear().add('./src/main-pro.js') //打包入口
      /**======== GZIP压缩 satrt ========*/
      config
        .plugin("CompressionPlugin")
        .use('compression-webpack-plugin', [{//gzip压缩
          filename: '[path][base].gz',
          algorithm: 'gzip',
          test: /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i, // 要压缩的文件（正则）
          threshold: 10240,  // 最小文件开启压缩 10k
          deleteOriginalAssets: false, // 不删除源文件
          minRatio: 0.8
        }])
        .end()
      /**======== GZIP压缩 end ========*/

      config
        .plugin('ScriptExtHtmlWebpackPlugin')
        .after('html')
        .use('script-ext-html-webpack-plugin', [{
          inline: /runtime\..*\.js$/
        }])
        .end()

      /**======== splitChunks模块分割,节省打包时间 ========*/
      config
        .optimization.splitChunks({
          chunks: 'all',
          cacheGroups: {
            libs: {
              name: 'chunk-libs',
              test: /[\\/]node_modules[\\/]/,
              priority: 10,
              chunks: 'initial' // only package third parties that are initially dependent
            },
            elementUI: {
              name: 'chunk-elementUI', // split elementUI into a single package
              priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
              test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
            },
            commons: {
              name: 'chunk-commons',
              test: resolve('src/components'), // can customize your rules
              minChunks: 3, //  minimum common number
              priority: 5,
              reuseExistingChunk: true
            }
          }
        })
      config.optimization.runtimeChunk('single')
    }
    /**================== 生产环境 end ==================*/

    /**================== 开发环境 start ==================*/
    else {
      config.entry('app').clear().add('./src/main-dev.js')//打包入口
    }
    /**================== 开发环境 end ==================*/

  }
}
